import searchbar from './searchbar.js';
// import searchbar from './searchbar.js';
import urlParser from '../../util/urlParser.js';
import funcs from '../../util/funcs';
import places from '../../places/places.js';
let state;
function showPlaceSuggestions(text, input, event) {
  // use the current tab's url for history suggestions, or the previous tab if the current tab is empty
  var url =state.tabs(state.tab_value).url;

  if (!url) {
    return;
  }
  places.getPlaceSuggestions(url, function (results) {
    searchbar.reset('placeSuggestions');

    var tabList = state.tabs.map(function (tab) {
      return tab.url;
    });

    results = results.filter(function (item) {
      return tabList.indexOf(item.url) === -1;
    });

    results.slice(0, 4).forEach(function (result) {
      searchbar.addResult('placeSuggestions', {
        title: urlParser.prettyURL(result.url),
        secondaryText: funcs.getRealTitle(result.title),
        url: result.url,
        delete: function () {
          places.deleteHistory(result.url);
        },
      });
    });
  });
}

function initialize(dispatch,state) {
  state=state;
  searchbar.register('placeSuggestions', {
    index: 1,
    trigger: function (text) {
      r=!text
      console.log(text)
      console.log("place suggestion trigger: "+r);
      return r;
    },
    showResults: showPlaceSuggestions,
  });
}

export default { initialize };
